package com.busines.controller;

import java.awt.image.BufferedImage;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.busines.alipay.AliPayApi;
import com.busines.alipay.AliPayUtil;
import com.common.util.DateUtils;
import com.common.util.RandomUtil;

@Controller
@RequestMapping("alipay")
public class PrePayController {

	private static Logger log = LoggerFactory.getLogger(PrePayController.class);
	
	@RequestMapping("test")
	@ResponseBody
	public void test(){
		log.info("==========开始进行测试=========");
	}
	
	@RequestMapping(value="/foundZFBOrder", produces = "application/json;charset=UTF-8")  
    @ResponseBody  
    public String foundZFBOrder(HttpServletRequest request){  
        //支付宝信息  
        String aliPayInfo = request.getParameter("aliPayInfo");  
        //金额  
        String money = request.getParameter("money");  
        //订单名称  
        String orderName = request.getParameter("orderName");  
        //订单编号  
        String orderNumber = request.getParameter("orderNumber");  
          
        //判断是否生成过支付宝信息  
        if(StringUtils.isEmpty(aliPayInfo)){  
            //生成支付宝信息  
            aliPayInfo = AliPayUtil.orderInfo(money, orderName, orderNumber);  
              
        }
          return aliPayInfo;
    }
	
	@RequestMapping("prePay")
	public void prePay(HttpServletRequest request,HttpServletResponse resp){
		String logofile="C:/Users/youxiang/Desktop/banner1.png";
		String tradeNo = "Order"+DateUtils.getNowStrDate1()+RandomUtil.randomNext(8);
		
		String subject = "Javen 支付宝扫码支付测试";
        String totalAmount = RandomUtil.randomThree();
        String storeId = "222222222";
        String notifyUrl = AliPayApi.NOTIFY_DOMAIN + "/alipay/precreate_notify";

        AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
        model.setSubject(subject);
        model.setTotalAmount(totalAmount);
        model.setStoreId(storeId);
        model.setTimeoutExpress("1m");
        model.setOutTradeNo(tradeNo);
        try {
            String resultStr = AliPayApi.tradePrecreatePay(model, notifyUrl);
            JSONObject jsonObject = JSONObject.parseObject(resultStr);
            if(jsonObject.getJSONObject("alipay_trade_precreate_response").getIntValue("code")!=10000){
            	resp.getWriter().write(jsonObject.toJSONString());
            	return;
            }
            String qr_code = jsonObject.getJSONObject("alipay_trade_precreate_response").getString("qr_code");
            //String qr_code = jsonObject.getJSONObject("alipay_trade_precreate_response").toJSONString();
            //resp.getWriter().write(qr_code);
            BufferedImage im = AliPayApi.createImage(qr_code,500,500,logofile);
            ImageIO.write(im, "jpg", resp.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
	}
	@RequestMapping("precreate_notify")
	@ResponseBody
	public String precreate_notify_url(HttpServletRequest request,HttpServletResponse resp){
		 try {
	            Map<String, String> map = AliPayApi.toMap(request);
	            for (Map.Entry<String, String> entry : map.entrySet()) {
	                System.out.println(entry.getKey()+" = "+entry.getValue());
	            }
	            boolean flag = AlipaySignature.rsaCheckV1(map, AliPayApi.public_key, AliPayApi.charset,
	                    AliPayApi.sign_type);
	            if (flag) {
	                // TODO
	                System.out.println("precreate_notify_url success");
	                return "success";
	            } else {
	                // TODO
	                System.out.println("precreate_notify_url failure");
	                return "failure";
	            }
	        } catch (AlipayApiException e) {
	            e.printStackTrace();
	            System.out.println("precreate_notify_url failure");
	            return "failure";
	        }
	}
	@RequestMapping("query")
	@ResponseBody
	public String queryOutTradeNo(HttpServletRequest req,HttpServletResponse resp){
		AlipayTradeQueryModel model = new AlipayTradeQueryModel();
		model.setOutTradeNo(req.getParameter("outTradeNo"));
		try {
			resp.getWriter().write(AliPayApi.tradeQuery(model));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
